package com.mdp.tpa.wechat.wxpub.service;

import java.util.Map;

import com.mdp.tpa.pub.client.SysClientService;
import com.mdp.tpa.pub.entity.SysUserTpa;
import com.mdp.tpa.pub.entity.SysUserTpaInvite;
import com.mdp.tpa.pub.service.InviteCacheService;
import com.mdp.tpa.wechat.api.AccessTokenService;
import com.mdp.tpa.wechat.api.SubscribeEventService;
import com.mdp.tpa.wechat.api.WxUserService;
import com.mdp.tpa.wechat.client.service.WxpubLoginHelpService;
import com.mdp.tpa.wechat.config.WxpubProperties;
import com.mdp.tpa.wechat.entity.AccessToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.mdp.tpa.client.entity.AppTpAuth;
import com.mdp.tpa.client.service.AppTpAuthService;


@Service
public class SubscribeEventServiceImpl implements SubscribeEventService {
	Log log=LogFactory.getLog(SubscribeEventServiceImpl.class); 
 
	@Autowired
	WxUserService wxApiUser;

	@Autowired
	AccessTokenService accessTokenService;

	@Autowired
	WxpubLoginHelpService wxpubLoginHelpService;

	@Autowired
	SysClientService sysClientService;

	@Autowired
	InviteCacheService stateService;

	@Autowired
	WxpubProperties wxpubProperties;
	 

	@Override
	public void doEvent(String event, String msgType, String fromUser, String toUser, String createTime,
			Map<String, Object> info) {
		 if(event.equals("subscribe")){
			 this.subscribe(event, msgType, fromUser, toUser, createTime, info);
		 }else if(event.equals("unsubscribe")){
			 this.unsubscribe(event, msgType, fromUser, toUser, createTime, info);
		 } 
		
	}
	 

	@Async
	@Override
	public void subscribe(String event, String msgType, String fromUser, String toUser, String createTime,
			Map<String, Object> info) {
 		Map<String,Object> userInfo=wxApiUser.getUserinfo( fromUser);
		String state=stateService.createInviteId("subscribe");
		SysUserTpaInvite invite=new SysUserTpaInvite();
		invite.setInviteId(state);
		stateService.setInvite(state,invite);
		SysUserTpa tpa=wxpubLoginHelpService.wechatUserInfoConvertToUserTpa(userInfo);
		SysUserTpa tpadb=sysClientService.getSysUserTpaByOpenid(tpa.getOpenid());
		tpa.setAppType("wxpub");
		tpa.setAppid(wxpubProperties.getAppid());
		sysClientService.registerUserByTpa(state,tpa,tpadb!=null);


	}
	
	@Override
	public void unsubscribe(String event, String msgType, String fromUser, String toUser, String createTime,
			Map<String, Object> info) {
		// TODO Auto-generated method stub
		
	}

}
